<?php

/**
 * 
 * @project     : innoTweets 1.0
 * @author      : Dino (DBK)
 * 
 * @package     : Tweet
 * @description : Albums for mobile
 * 
 */
if (!defined('BASEPATH')) {
  exit('No direct script access allowed');
}

class Album extends MOBILE_AUTH_Controller {

  /**
   * Get albums 
   */
  public function albums() {

    // Setting limit count
    $album_limit = $this->input->get('limit', TRUE);
    $album_limit = (int) (!empty($album_limit) && is_numeric($album_limit)) ? $album_limit : 10;
    $album_offset = $this->input->get('offset', TRUE);
    $album_offset = (int) (!empty($album_offset) && is_numeric($album_offset)) ? $album_offset : 0;
    $album_type = $this->input->get('type', TRUE);

    // Getting album type
    if ($album_type == 2) {
      $get_albums = $this->album_model->get_albums($this->mobile_current_user['user_id'], $album_limit);
    } else {
      $get_albums = $this->album_model->get_albums(null, $album_limit);
    }

    $this->response['status'] = 1;
    $this->response['message'] = 'Success';
    $this->response['data'] = array(
        'albums' => $get_albums['result']
    );
  }

  /**
   * Create new album
   * 
   */
  public function create() {

    // Checking request type
    if ($this->is_post()) {

      $image_upload = array();

      // Getting album details
      $album_name = $this->sanitize($this->input->post('album_name', TRUE));
      $album_status = $this->sanitize($this->input->post('album_status', TRUE));
      $album_status = ($album_status) ? $album_status : 2;

      // Checking inputs
      if (!empty($album_name) && strlen($album_name) <= 250 && !empty($_FILES) && is_array($_FILES)) {

        // Prepraing upload config & upload files
        $config = array();
        $config['upload_path'] = 'assets/temp/';
        $config['allowed_types'] = 'gif|jpg|png|mpg|mpeg|avi|mp4|3g2|3gp|flv';
        $config['max_size'] = '256000';
        $this->load->library('upload');
        $this->upload->initialize($config);
        $this->upload->do_multi_upload("album_image");
        $image_upload = $this->upload->get_multi_upload_data();
        $err_msg = $this->upload->display_errors();

        if (!empty($image_upload) && is_array($image_upload)) {

          // Creating album
          $set_album = $this->album_model->set_album($album_name, $this->mobile_current_user['user_id'], $album_status);

          if (!empty($set_album['result'])) {

            $album_id = $set_album['result']['album_id'];

            // Creating album directory
            @mkdir('assets/albums/' . $album_id . '/', 0777, TRUE);

            $count = 0;
            $this->load->library('image_lib');

            // Processing album photos and videos
            foreach ($image_upload as $image_data) {

              $rand_string = md5(microtime() . rand(11111, 99999));

              if (($image_data['file_type'] == 'image/jpeg') || ($image_data['file_type'] == 'image/gif') || ($image_data['file_type'] == 'image/png')) {
                // Saving images to album
                $image_file_name = $rand_string . '.jpg';
                $thumb_file_name = $rand_string . '_thumb.jpg';
                $new_image_file = 'assets/albums/' . $album_id . '/' . $image_file_name;
                $new_thumb_file = 'assets/albums/' . $album_id . '/' . $thumb_file_name;
                $this->create_image($image_data['full_path'], $new_image_file);
                $this->create_thumb($image_data['full_path'], $new_thumb_file, $image_data['image_width'], $image_data['image_height']);
                if (file_exists($new_image_file)) {
                  $count++;
                  $this->album_model->add_photo($album_id, $image_file_name, 1);
                }
              } else {
                // Saving video to album
                $video_file_name = $rand_string . '.flv';
                $video_thumb_file_name = $rand_string . '_thumb.jpg';
                $new_video_file = 'assets/albums/' . $album_id . '/' . $video_file_name;
                $new_video_thumb_file = 'assets/albums/' . $album_id . '/' . $video_thumb_file_name;
                $this->create_video($image_data['full_path'], $new_video_file);
                $this->create_video_thumb($image_data['full_path'], $new_video_thumb_file);
                if (file_exists($new_video_file)) {
                  $count++;
                  $this->album_model->add_photo($album_id, $video_file_name, 2);
                }
              }

              // Remove temp file
              @unlink($image_data['full_path']);
            }

            $get_album = $this->album_model->get_album($album_id);
            $get_photos = $this->album_model->get_photos($album_id);

            // Respond 
            $this->response['status'] = 1;
            $this->response['message'] = 'Success';
            $this->response['data'] = array(
                'album' => $this->album_response($get_album['result']),
                'photos' => $this->photo_response($get_photos['result'])
            );
          } else {
            $this->response['message'] = 'Unable to create album';
          }
        } else {
          $this->response['message'] = 'Unable to upload files - ' . $err_msg;
        }
      } else {
        $this->response['message'] = 'Invalid tilte or files';
      }
    } else {
      $this->response['message'] = 'Invalid request';
    }
  }

  /**
   * Update user album
   * 
   */
  public function update($album_id = null) {

    // Checking request type
    if ($this->is_post()) {

      $image_upload = array();

      // Getting album details
      $album_name = $this->sanitize($this->input->post('album_name', TRUE));
      $album_status = $this->sanitize($this->input->post('album_status', TRUE));
      $album_status = ($album_status) ? $album_status : 2;

      // Checking inputs
      if (!empty($album_name) && strlen($album_name) <= 250 && !empty($_FILES) && is_array($_FILES)) {

        $get_album = $this->album_model->get_album($album_id);
        if (!empty($get_album['result']) && ($get_album['result']['album_user_id'] == $this->mobile_current_user['user_id'])) {

          // Updating album details
          $update_album = $this->album_model->update_album($album_id, $album_name, $album_status);

          // Prepraing upload config & upload files
          $config = array();
          $config['upload_path'] = 'assets/temp/';
          $config['allowed_types'] = 'gif|jpg|png|mpg|mpeg|avi|mp4|3g2|3gp|flv';
          $config['max_size'] = '256000';
          $this->load->library('upload');
          $this->upload->initialize($config);
          $this->upload->do_multi_upload("album_image");
          $image_upload = $this->upload->get_multi_upload_data();
          $err_msg = $this->upload->display_errors();

          if (!empty($image_upload) && is_array($image_upload)) {

            // Creating album directory
            @mkdir('assets/albums/' . $album_id . '/', 0777, TRUE);

            $count = 0;
            $this->load->library('image_lib');

            // Processing album photos and videos
            foreach ($image_upload as $image_data) {

              $rand_string = md5(microtime() . rand(11111, 99999));

              if (($image_data['file_type'] == 'image/jpeg') || ($image_data['file_type'] == 'image/gif') || ($image_data['file_type'] == 'image/png')) {
                // Saving images to album
                $image_file_name = $rand_string . '.jpg';
                $thumb_file_name = $rand_string . '_thumb.jpg';
                $new_image_file = 'assets/albums/' . $album_id . '/' . $image_file_name;
                $new_thumb_file = 'assets/albums/' . $album_id . '/' . $thumb_file_name;
                $this->create_image($image_data['full_path'], $new_image_file);
                $this->create_thumb($image_data['full_path'], $new_thumb_file, $image_data['image_width'], $image_data['image_height']);
                if (file_exists($new_image_file)) {
                  $count++;
                  $this->album_model->add_photo($album_id, $image_file_name, 1);
                }
              } else {
                // Saving video to album
                $video_file_name = $rand_string . '.flv';
                $video_thumb_file_name = $rand_string . '_thumb.jpg';
                $new_video_file = 'assets/albums/' . $album_id . '/' . $video_file_name;
                $new_video_thumb_file = 'assets/albums/' . $album_id . '/' . $video_thumb_file_name;
                $this->create_video($image_data['full_path'], $new_video_file);
                $this->create_video_thumb($image_data['full_path'], $new_video_thumb_file);
                if (file_exists($new_video_file)) {
                  $count++;
                  $this->album_model->add_photo($album_id, $video_file_name, 2);
                }
              }

              // Remove temp file
              @unlink($image_data['full_path']);
            }

            $get_album = $this->album_model->get_album($album_id);
            $get_photos = $this->album_model->get_photos($album_id);

            // Respond 
            $this->response['status'] = 1;
            $this->response['message'] = 'Success';
            $this->response['data'] = array(
                'album' => $this->album_response($get_album['result']),
                'photos' => $this->photo_response($get_photos['result'])
            );
          } else {
            $this->response['message'] = 'Unable to upload files - ' . $err_msg;
          }
        } else {
          $this->response['message'] = 'Permission denied';
        }
      } else {
        $this->response['message'] = 'Invalid tilte or files';
      }
    } else {
      $this->response['message'] = 'Invalid request';
    }
  }

  /**
   * Delete photos
   * 
   */
  public function delete_photos($item = null) {
    if ($this->is_post()) {
      $delete_photo_ids = $this->input->post('delete_photo_ids', TRUE);
      if (!empty($delete_photo_ids) && is_array($delete_photo_ids)) {
        foreach ($delete_photo_ids as $delete_photo_id) {
          $get_photo = $this->album_model->get_photo_by_id($delete_photo_id);
          if ($get_photo['status'] == 1 && !empty($get_photo['result']) && ($get_photo['result']['album_user_id'] == $this->mobile_current_user['user_id'])) {
            $image_file = 'assets/albums/' . $get_photo['result']['album_id'] . '/' . $get_photo['result']['photo_file'];
            $thumb_file = 'assets/albums/' . $get_photo['result']['album_id'] . '/' . substr($get_photo['result']['photo_file'], 0, 32) . '_thumb.jpg';
            if ($get_photo['result']['photo_video_type'] == 2) {
              $this->like_model->del_likes_by_post('video', $get_photo['result']['photo_id']);
              $this->comment_model->del_comment_by_post('video', $get_photo['result']['photo_id']);
            } else {
              $this->like_model->del_likes_by_post('photo', $get_photo['result']['photo_id']);
              $this->comment_model->del_comment_by_post('photo', $get_photo['result']['photo_id']);
            }
            $delete_photo = $this->album_model->delete_photo($delete_photo_id, $get_photo['result']['album_id']);
            if ($delete_photo['status'] == 1 && !empty($delete_photo['result'])) {
              @unlink($image_file);
              @unlink($thumb_file);
              $this->response['status'] = 1;
              $this->response['message'] = 'Success';
              $this->response['data'] = true;
            }
          } else {
            $this->response['message'] = 'Permission denied for some photos';
          }
        }
      } else {
        $this->response['message'] = 'Photo ids required';
      }
    } else {
      $this->response['message'] = 'Invalid request';
    }
  }

  /**
   * Create the image file on the given location from an image.
   * Also resize the new image
   * 
   */
  private function create_image($orig_file, $new_file) {
    $config = array();
    $config['image_library'] = 'gd2';
    $config['source_image'] = $orig_file;
    $config['maintain_ratio'] = TRUE;
    $config['new_image'] = $new_file;
    $config['width'] = 1024;
    $config['height'] = 768;
    $this->image_lib->clear();
    $this->image_lib->initialize($config);
    $this->image_lib->resize();
  }

  /**
   * Create a square thumb of the image
   * 
   */
  private function create_thumb($orig_file, $new_file, $orig_width, $orig_height) {

    // Image croping
    if ($orig_width > $orig_height) {
      $new_width = $orig_height;
      $new_height = $orig_height;
      $x = @round(($orig_width / 2) - ($new_width / 2));
      $y = 0;
    } elseif ($orig_height > $orig_width) {
      $new_width = $orig_width;
      $new_height = $orig_width;
      $x = 0;
      $y = @round(($orig_height / 2) - ($new_height / 2));
    } else {
      $new_width = $orig_width;
      $new_height = $orig_height;
      $x = 0;
      $y = 0;
    }

    // Croping
    $config = array();
    $config['image_library'] = 'gd2';
    $config['source_image'] = $orig_file;
    $config['new_image'] = $new_file;
    $config['width'] = $new_width;
    $config['height'] = $new_height;
    $config['x_axis'] = $x;
    $config['y_axis'] = $y;
    $this->image_lib->clear();
    $this->image_lib->initialize($config);
    $this->image_lib->crop();

    // Resizing
    $config = array();
    $config['image_library'] = 'gd2';
    $config['source_image'] = $new_file;
    $config['new_image'] = $new_file;
    $config['maintain_ratio'] = FALSE;
    $config['width'] = 320;
    $config['height'] = 240;
    $this->image_lib->clear();
    $this->image_lib->initialize($config);
    $this->image_lib->resize();
  }

  /**
   * Create a new flv video file from the provied video file (Required ffmpeg)
   * 
   */
  private function create_video($input_file = NULL, $output_file = NULL) {
    $command_video = "ffmpeg -i " . escapeshellarg((string) $input_file) . " -f flv -s 1024x768 " . escapeshellarg((string) $output_file) . " &";
    system($command_video);
    if (file_exists($output_file)) {
      return TRUE;
    } else {
      return FALSE;
    }
  }

  /**
   * Create thumb image of the flv video file (Required ffmpeg)
   * 
   */
  private function create_video_thumb($input_file = NULL, $output_file = NULL) {

    if (!file_exists($output_file)) {
      $this->load->library('ffmpeg');
      $this->ffmpeg->clear()->input($input_file)->thumb('320x240', 1, 10)->output($output_file)->ready();
    }

    if (!file_exists($output_file)) {
      $command_thumb = "ffmpeg -i " . escapeshellarg((string) $input_file) . " -deinterlace -an -ss 1 -t 00:00:05 -r 1 -y -s 320x240 -vcodec mjpeg -f mjpeg " . escapeshellarg((string) $output_file) . " 2>&1";
      system($command_thumb);
    }

    if (!file_exists($output_file)) {
      $command_thumb = "ffmpeg -i " . escapeshellarg((string) $input_file) . " -deinterlace -an -ss 1 -f mjpeg -t 1 -r 1 -y -s 320x240 " . escapeshellarg((string) $output_file) . " 2>&1";
      system($command_thumb);
    }

    if (!file_exists($output_file)) {
      $command_thumb = "ffmpeg -itsoffset -105 -i " . escapeshellarg((string) $input_file) . " -vcodec mjpeg -vframes 1 -an -f rawvideo -s 320x240 " . escapeshellarg((string) $output_file) . " 2>&1";
      system($command_thumb);
    }

    if (file_exists($output_file)) {
      return TRUE;
    } else {
      return FALSE;
    }
  }

  /**
   * Album response
   * 
   */
  private function album_response($album = array()) {
    $album_response = array();
    $album_response['album_id'] = $album['album_id'];
    $album_response['album_name'] = $album['album_name'];
    $album_response['album_date'] = $album['album_date'];
    $album_response['user_id'] = $album['user_id'];
    $album_response['user_name'] = $album['user_name'];
    $album_response['user_image'] = site_url('assets/photos/' . $album['user_image']);
    return $album_response;
  }

  /**
   * Photo response
   * 
   */
  private function photo_response($photos = array()) {
    $photos_response = array();
    foreach ($photos as $photo) {
      $photo_response = array();
      $photo_response['photo_id'] = $photo['photo_id'];
      $photo_response['photo_type'] = $photo['photo_video_type'];
      $photo_response['photo_file'] = site_url('assets/albums/' . $photo['photo_album_id'] . '/' . $photo['photo_file']);
      $photo_response['photo_thumbnail'] = site_url('assets/albums/' . $photo['photo_album_id'] . '/' . substr($photo['photo_file'], 0, 32) . '_thumb.jpg');
      $photos_response[] = $photo_response;
    }
    return $photos_response;
  }

  /**
   * Responding Json
   * 
   */
  public function __destruct() {
    echo json_encode($this->response);
  }

}

?>